package com.ztjava.auth.validator;

import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.auth.service.AuthService;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseValidator;
import com.ztjava.core.bean.sub.CaptchaBean;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.core.utiliy.StringUtil;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.plugin.event.EventKit;
import com.ztjava.plugin.event.EventTag;
import com.ztjava.plugin.event.core.RequestEvent;

public class ForgetValidator extends BaseValidator{

	private static AuthService authService = Duang.duang(AuthService.class);
	@Override
	protected void validate(Controller c) {
		setShortCircuit(true);
		String portal = c.getClass().getAnnotation(UserController.class).portal().toUpperCase();
		if(ViewTool.param("AUTH_"+portal+"_FORGET_ONOFF","OFF").equals("OFF")){
			addError(Constant.MESSAGE,"暂停找回密码！");
			return;
		}
		String type = ViewTool.param("AUTH_"+portal+"_REGISTER_TYPE");
		if(type.equals("PHONE")){
			
			validateRequiredString("to",Constant.MESSAGE, "请输入手机号!");
			validateMobilePattern("to", Constant.MESSAGE, "手机号格式不正确！");
			validateRequiredString("auth",Constant.MESSAGE, "请输入短信验证码!");
			
		}else if(type.equals("EMAIL")){
			
			validateRequiredString("to", Constant.MESSAGE, "请输入邮箱！");
			validateEmail("to", Constant.MESSAGE, "邮箱格式不正确！");
			validateRequiredString("auth",Constant.MESSAGE, "请输入邮箱验证码!");
			
		}else {
			addError(Constant.MESSAGE,"无法找回密码，请联系管理员");
		}
		validateRequiredString("password", Constant.MESSAGE, "请输入新密码！");
		validateString("password", 6, 30, Constant.MESSAGE, "新密码必须6-30个字符!");
		if(StringUtil.isNumeric(c.getPara("password"))){
			addError(Constant.MESSAGE, "密码不能全部为数字！");
		}
		//是否已被注册
		AuthUser authUser = authService.checkUserAndType(portal, type, c.getPara("to"));
		if(authUser==null){
			addError(Constant.MESSAGE,"尚未注册，无法找回密码");
		}
		
		if(type.equals("PHONE")||type.equals("EMAIL")){
			//检查验证码
			Ret ret = EventKit.postRemoteOnly(EventTag.COMMON_PUSH_CHECKCAPTCHA,
					new RequestEvent(new CaptchaBean(portal, c.getPara("to"), type+"FORGET", c.getPara("auth"))));
			if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)){
				addError(Constant.MESSAGE,ret.getStr(Constant.MESSAGE));
			}
		}
		c.setAttr("authUser", authUser);
	}

}
